package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntityGameParam;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.manager.system.GameParamTypeConfigManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.bi.support.Session;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.datanucleus.util.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.transaction.Transactional;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 游戏参数配置
 * 
 * @author marin
 * @date 2015-09-29
 */
@Controller
@Scope("view")
public class GameParamConfigAction {
	private final String tmpuploaddir = "/usr/local/tomcat/upload/";

    private EntityGameParam entity;
	private Map<String, Integer> queryGameParamTypeItmes;
	private List<EntityGameParam> list;

	private static File file;
	private int uploadparamtype;
	
	@Autowired
	private GameParamConfigManager gameParamConfigManager;
	
	@Autowired
	private Session session;
	@Autowired
	private SysLogManager sysLogManager;
	
	@Autowired
	public void init() {
		sysLogManager.addLog(session.getUserName(), "游戏参数配置");
		
		initData();
		
		search(entity);
	}
	
	private void initData() {
		uploadparamtype = 0;
		file = null;
		
		entity = new EntityGameParam();
		//entity.setParamtype(GameParamTypeConfigManager.FIRST_ID);
		
		queryGameParamTypeItmes = GameParamTypeConfigManager.gameParamTypeItmes;
		
		list = GameParamConfigManager.GAME_PARAM_LIST;
	}
	
	public void search(EntityGameParam l) {
		list = gameParamConfigManager.getGameParamByEntity(l == null ? entity : l);
		if (list != null && list.size() > 0) {
			Collections.sort(list, new EntityGameParam().comparator);
		}
	}
	
	public String getParamIDStr(EntityGameParam l) {
		String suffix = "";
		
		if (l.getParamtype() == 1) {
			for (CommonGameParam en : CommonGameParam.values()) {
				if ((en.COMMONID + "").equals(l.getParamid())) {
					suffix = " (" + en.DESC + ")";
					break;
				}
			}
		}
		
		return l.getParamid() + suffix;
	}
	
	public void upload(FileUploadEvent event) throws IOException {
        System.out.println("########################## upload file: ");
        UploadedFile ufile = event.getFile();
        System.out.println("########################## file is null: " + (ufile != null));
        if (ufile != null) {
            InputStream inputStream = ufile.getInputstream();

            File tmpdir = new File(tmpuploaddir);
            if (!tmpdir.exists()) {
                tmpdir.mkdir();
            }

            System.out.println("########################## tmpuploaddir: " + tmpuploaddir);

            file = new File(tmpuploaddir + ufile.getFileName() + System.currentTimeMillis());
            file.createNewFile();

            OutputStream outputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            while((inputStream.read(b)) != -1){
                outputStream.write(b);
            }
            inputStream.close();
            outputStream.close();
        }

        System.out.println("上传了文件：" + file == null ? file : file.getAbsolutePath());
	}
	
	public void parseExcel() {
		FacesContext context = FacesContext.getCurrentInstance();
		
		if (uploadparamtype == 0) {
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "请选择参数类型！"));
        	return;
		}
		
        if(file != null && file.exists()) {
        	try {
				List<EntityGameParam> tmp = parseUploadedExcel(file);
				
				if (tmp != null && tmp.size() > 0) {
					int ttype = tmp.get(0).getParamtype();
					if (uploadparamtype != ttype) {
						context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "参数类型与文件中类型不一致！"));
			        	return;
					}
					
					Map<String, EntityGameParam> tm = gameParamConfigManager.getIdGameParamMapByType(String.valueOf(ttype),0);

					for (EntityGameParam e : tmp) {
						String tid = e.getParamid();
						String tvalue = e.getParamname();

						EntityGameParam t = tm.get(tid);
						if (t == null) {
							t = new EntityGameParam();
							t.setParamid(tid);
							t.setParamname(tvalue);
							t.setParamtype(ttype);
							t.setSeq(e.getSeq());

							gameParamConfigManager.persist(t);
						} else {
							t.setParamname(tvalue);
							gameParamConfigManager.merge(t);
						}
					}
					
					gameParamConfigManager.init();
					initData();
					
					EntityGameParam q = new EntityGameParam();
					q.setParamtype(tmp.get(0).getParamtype());
					search(q);
					
					context.addMessage(null, new FacesMessage("解析成功！"));
				}
			} catch (InvalidFormatException e) {
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "文件内容格式错误！"));
				e.printStackTrace();
			} catch (IOException e) {
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "解析文件错误！"));
				e.printStackTrace();
			} catch (Exception e) {
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "解析文件错误！"));
				e.printStackTrace();
			} finally {
                if (file != null && file.exists()) {
                    file.delete();
                }
            }
        } else {
        	context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "请上传文件！"));
        	return;
		}
    }
	
	public List<EntityGameParam> parseUploadedExcel(File file) throws Exception {
		FacesContext context = FacesContext.getCurrentInstance();
		List<EntityGameParam> result = new ArrayList<>();
		
		InputStream input = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(input);

		Sheet tempSheet = wb.getSheetAt(0);
		if (tempSheet == null) {
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "数据错误！"));
			IOUtils.closeQuietly(input);
			
			return result;
		}
		
		String firstType = "";
		int rowNum = tempSheet.getLastRowNum();// 获得总行数
		for (int i = 0; i <= rowNum; i++) {
			Row row = tempSheet.getRow(i);
			if (row == null) {
				continue;
			}
			
			String type = ExcelUtils.getCellValue(row.getCell(0));
			String key = ExcelUtils.getCellValue(row.getCell(1));
			String value = ExcelUtils.getCellValue(row.getCell(2));
            String sort = ExcelUtils.getCellValue(row.getCell(3));
			
			if ("".equals(type) || "".equals(key) || "".equals(key)) {
				continue;
			}
			
			if (i == 0) {
				firstType = type;
			} else {
				if (!firstType.equals(type)) {
					context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "类型列数据不一致！"));
					IOUtils.closeQuietly(input);
					
					return null;
				}
			}
			
			EntityGameParam e = new EntityGameParam();
			e.setParamtype(Integer.parseInt(type));
			e.setParamid(key);
			e.setParamname(value);
			e.setSeq(StringUtils.isEmpty(sort) ? 0 : Integer.parseInt(sort));
			
			result.add(e);
		}
		
		IOUtils.closeQuietly(input);
		
		return result;
	}

	public void add() {
		FacesContext context = FacesContext.getCurrentInstance();
		
		if (entity.getParamtype() == 0) {
			context.addMessage(null, new FacesMessage("请选择参数类型！"));
			return;
		}
		
		if (entity.getParamname() == null || "".equals(entity.getParamname())) {
			context.addMessage(null, new FacesMessage("值不能为空！"));
			return;
		}
		
		if (GameParamConfigManager.canAdd(entity, true)) {
			gameParamConfigManager.persist(entity);
			context.addMessage(null, new FacesMessage("添加成功！"));
			
			EntityGameParam q = new EntityGameParam();
			q.setParamtype(entity.getParamtype());
			
			gameParamConfigManager.init();
			initData();
			
			search(q);
		} else {
			context.addMessage(null, new FacesMessage("ID或名称重复！"));
		}
	}

	public void modify(EntityGameParam e) {
		FacesContext context = FacesContext.getCurrentInstance();
		
		if (GameParamConfigManager.canAdd(e, false)) {
			gameParamConfigManager.merge(e);
			context.addMessage(null, new FacesMessage("修改成功！"));
		} else {
			context.addMessage(null, new FacesMessage("名称重复或未修改！"));
		}
		
		gameParamConfigManager.init();
		initData();
        EntityGameParam s = new EntityGameParam();
        s.setParamtype(e.getParamtype());
        search(s);
	}
	
	@Transactional
	public void delete(EntityGameParam e) {
		EntityGameParam q = new EntityGameParam();
		q.setParamtype(e.getParamtype());
		
		FacesContext context = FacesContext.getCurrentInstance();
		
		gameParamConfigManager.getEntityManager().remove(gameParamConfigManager.getEntityManager().merge(e));
		
		gameParamConfigManager.init();
		initData();
		
		search(q);
		
		context.addMessage(null, new FacesMessage("删除成功！"));
	}

	public EntityGameParam getEntity() {
		return entity;
	}

	public void setEntity(EntityGameParam entity) {
		this.entity = entity;
	}

	public Map<String, Integer> getQueryGameParamTypeItmes() {
		return queryGameParamTypeItmes;
	}

	public void setQueryGameParamTypeItmes(Map<String, Integer> queryGameParamTypeItmes) {
		this.queryGameParamTypeItmes = queryGameParamTypeItmes;
	}

	public List<EntityGameParam> getList() {
		return list;
	}

	public void setList(List<EntityGameParam> list) {
		this.list = list;
	}
	
	public int getUploadparamtype() {
		return uploadparamtype;
	}

	public void setUploadparamtype(int uploadparamtype) {
		this.uploadparamtype = uploadparamtype;
	}
}
